package com.example.demo5rbac.config;

import com.example.demo5rbac.config.dynamic.CustomAuthorizationManager;
import com.example.demo5rbac.config.dynamic.JsonAccessDeniedHandler;
import com.example.demo5rbac.config.dynamic.JsonAuthenticationEntryPoint;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

//    @Bean
//    UserDetailsService userDetailsService() {
//        InMemoryUserDetailsManager users = new InMemoryUserDetailsManager();
//        users.createUser(User.withUsername("user").password("{noop}123456").roles("user").build());
////        users.createUser(User.withUsername("admin").password("{noop}123456").roles("admin").build());
//        return users;
//    }
//    @Bean("userDetailsService2")
//    UserDetailsService userDetailsService2() {
//        InMemoryUserDetailsManager users = new InMemoryUserDetailsManager();
////        users.createUser(User.withUsername("user").password("{noop}123456").roles("user").build());
//        users.createUser(User.withUsername("admin").password("{noop}123456").roles("admin").build());
//        return users;
//    }
    @Autowired
    CustomAuthorizationManager customAuthorizationManager;
    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // login放行，其他请求验证
        http.authorizeHttpRequests(authorize->{
            authorize.requestMatchers("login").permitAll().anyRequest().access(customAuthorizationManager);
        });
//        http.csrf().disable();
        http.exceptionHandling(exception ->
                exception.accessDeniedHandler(new JsonAccessDeniedHandler()).authenticationEntryPoint(new JsonAuthenticationEntryPoint())
                );


        return http.build();

    }
}
